<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <!-- vue3新增了一个this.$watch()方法，用于动态地添加和取消侦听 -->
      <!-- const unwatch = this.$watch("变量", 回调函数) -->
      <!-- 取消 unwatch() -->
      <h2>侦听器的补充</h2>
      <p>count: {{ count }}</p>
      <button @click="count++">btn</button>

      <button @click="fn">开始侦听</button>
      <button @click="fn2">结束侦听</button>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      const { createApp } = Vue;

      let unWatch = [];
      let i = 0;
      // let openWatch = false;

      createApp({
        data() {
          return {
            count: 3,
          };
        },
        // created() {
        //   this.$watch("count", (newVal) => {
        //     console.log(newVal);
        //   });
        // },
        methods: {
          fn() {
            // if (!openWatch) {
            //   console.log("侦听开始了");
            //   unWacth = this.$watch("count", (newVal) => {
            //     console.log(newVal);
            //   });
            //   // openWatch = true;
            // }

            unWatch[i] = this.$watch("count", (val) => {
              console.log(val);
            });
            i++;
          },
          fn2() {
            // console.log(unWatch);
            // unWacth();
            // openWatch = false;

            unWatch.forEach((item) => {
              item();
            });
          },
        },
      }).mount("#app");
    </script>
  </body>
</html>
